package io.xxx.mario.task.job;

import io.xxx.mario.task.ExecutionMode;
import io.xxx.mario.task.Task;
import io.xxx.mario.task.TaskMapper;
import io.xxx.mario.task.TaskService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class OnceTaskPushJob extends QuartzJobBean {

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private TaskService taskService;

    @Override
    protected void executeInternal(@NonNull JobExecutionContext context) {
        List<Task> tasks = taskMapper.findArrivedTasks(ExecutionMode.ONCE.ordinal());
        tasks.parallelStream()
                .forEach(task -> {
                    log.info("任务开始执行[taskId:{},taskName:{}]", task.getId(), task.getName());
                    System.out.println(task);
                    try {
                        taskService.push(task);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
    }
}
